package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmNewsVo;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 分页条件查询文章列表
     *
     * @param dto
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        // 1. 校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        // 2. 分页条件查询
        // 2.1 设置分页参数
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        // 2.2 设置查询条件
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 2.2.1 状态
        lambdaQueryWrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        // 2.2.2 频道
        lambdaQueryWrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        // 2.2.3 查询关键字
        lambdaQueryWrapper.like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());
        // 2.2.4 发布时间
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        // 2.2.5 用户id
        lambdaQueryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        // 2.4 设置排序字段和方式
        lambdaQueryWrapper.orderByDesc(WmNews::getPublishTime)
                .orderByDesc(WmNews::getCreatedTime);
        page(page, lambdaQueryWrapper);
        // 3. 封装返回响应数据
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());
        return pageResponseResult;
    }


    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;
    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    /**
     * 提交，修改或者保存草稿
     *
     * @param dto
     */
    @Override
    // @Transactional
    public ResponseResult submitNews(WmNewsDto dto) {
        // 1. 校验参数
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 保存或修改文章(操作wm_news表)
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        // 判断是否存在封面图片
        if (!CollectionUtils.isEmpty(dto.getImages())) {
            String images = StringUtils.join(dto.getImages(), ","); // aaaa.jpg,aaa.png,aaa.jpg
            wmNews.setImages(images);
        }
        // 判断封面类型是否为自动
        if (wmNews.getType() == WemediaConstants.WM_NEWS_TYPE_AUTO) {
            wmNews.setType(null);
        }

        // 调用保存或者修改的方法
        saveOrUpdateNews(wmNews);

        // 3. 判断是否为保存草稿,是保存草稿，直接结束
        if (dto.getStatus() == 0) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        // 4. 不是草稿，保存文章内容和素材的关系
        // 提取内容中的图片
        List<String> images = extractMaterialFromContent(wmNews.getContent());
        saveRelativeInfoForContent(images, wmNews.getId());
        // 5. 不是草稿，保存文章封面和素材的关系
        saveRelativeInfoForCover(dto, wmNews, images);
        // 6. 进行文章审核，由于文章审核是异步执行，需要当前方法事务提交后才能开始执行，否则查询不到文章对象
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            // 当前事务提交后会自定回调此方法
            @Override
            public void afterCommit() {
                // wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
                wmNewsTaskService.addNewsToTask(wmNews.getId(), wmNews.getPublishTime());
            }
        });

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 文章的上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        // 1. 参数检查
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章id不为空");
        }
        // 2.按照id查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        // 3. 判断文章状态是否是已发表
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章不是发布状态，不能上下架");
        }
        // 4. 修改文章状态
        if (dto.getEnable() >= 0 && dto.getEnable() <= 1) {
            // update wm_news set enable = ? where id = ?;
            // wmNews.setEnable(dto.getEnable());
            // updateById(wmNews);
            LambdaUpdateWrapper<WmNews> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            // 设置参与修改的字段
            lambdaUpdateWrapper.set(WmNews::getEnable, dto.getEnable());
            // 设置修改条件
            lambdaUpdateWrapper.eq(WmNews::getId, dto.getId());
            update(lambdaUpdateWrapper);
            // 向kafka发送消息
            if (wmNews.getArticleId() != null){
                Map<String,Object> map = new HashMap<>();
                map.put("articleId",wmNews.getArticleId());
                map.put("enable",dto.getEnable());
                kafkaTemplate.send(WmNewsMessageConstants.TOPIC_DOWN_OR_UP, JSON.toJSONString(map));
            }

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else {
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_INVALID);
        }

    }

    /**
     * 保存文章封面和素材的关系
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> contentImages) {
        List<String> images = dto.getImages();
        // 判断是会否是自动
        if (dto.getType() == WemediaConstants.WM_NEWS_TYPE_AUTO) {
            if (contentImages.size() == 0) {
                // 无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if (contentImages.size() >= 1 && contentImages.size() < 3) {
                // 单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                // 从内容图片中获取一张作为封面图片
                images = contentImages.stream().limit(1).collect(Collectors.toList());
            }
            if (contentImages.size() >= 3) {
                // 多图
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                // 从内容图片中获取三张作为封面图片
                images = contentImages.stream().limit(3).collect(Collectors.toList());
            }
            if (!CollectionUtils.isEmpty(images)) {
                wmNews.setImages(StringUtils.join(images, ","));
            }

            // 修改状态和封面图片
            updateById(wmNews);
        }
        // 保存关系
        saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
    }

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 保存文章内容和素材的关联关系
     *
     * @param images 内容中的图片url集合
     * @param newsId 文章id
     */
    private void saveRelativeInfoForContent(List<String> images, Integer newsId) {
        if (CollectionUtils.isEmpty(images)) {
            return;
        }
        saveRelativeInfo(images, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    private void saveRelativeInfo(List<String> images, Integer newsId, Short type) {

        // 按照图片url地址，查询素材 select * from wm_material where url in(1.jpg,2.jpg)
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(WmMaterial::getUrl, images);
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(lambdaQueryWrapper);
        // 使用stream流将List<WmMaterial>转换成List<Integer>
        List<Integer> wmMaterialIds = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
        // 调用mapper进行关系保存
        wmNewsMaterialMapper.saveRelations(wmMaterialIds, newsId, type);
    }

    /**
     * 提取内容中的图片
     *
     * @param content
     * @return
     */
    private List<String> extractMaterialFromContent(String content) {
        List<String> images = new ArrayList<>();
        List<Map> maps = JSONArray.parseArray(content, Map.class);
        for (Map map : maps) {
            if ("image".equals(map.get("type"))) {
                String image = (String) map.get("value");
                images.add(image);
            }
        }
        return images;
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 保存或者修改文章
     *
     * @param wmNews
     */
    private void saveOrUpdateNews(WmNews wmNews) {
        // 1.补充属性
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((short) 1);
        // 2. 判断是否存在id
        if (wmNews.getId() == null) {
            // 2.1 保存，就向wm_news表插入数据
            save(wmNews);
        } else {
            // 3. 如果存在id，证明是修改
            // 3.1 按照文章id删除当前文章之前的素材关联关系
            LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(lambdaQueryWrapper);
            // 3.2 修改文章
            updateById(wmNews);
        }
    }

    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList2(NewsAuthDto dto) {
        //1.参数检查
        dto.checkParam();

        //记录当前页
        int currentPage = dto.getPage();

        //2.分页查询+count查询
        dto.setPage((dto.getPage()-1)*dto.getSize());
        List<WmNewsVo> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        int count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(currentPage,dto.getSize(),count);
        responseResult.setData(wmNewsVoList);
        return responseResult;
    }

    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findOne(Integer id) {
        //1.检查参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.结果返回
        return ResponseResult.okResult(wmNews);
    }

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1.检查参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.查询用户信息
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());

        //4.封装vo返回
        WmNewsVo vo = new WmNewsVo();
        //属性拷贝
        BeanUtils.copyProperties(wmNews,vo);
        if(wmUser != null){
            vo.setAuthorName(wmUser.getName());
        }

        ResponseResult responseResult = new ResponseResult().ok(vo);

        return responseResult;
    }

    /**
     * 文章审核，修改状态
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {
        //1.检查参数
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.修改文章的状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        //审核成功，则需要创建app端文章数据，并修改自媒体文章
        if(status.equals(WemediaConstants.WM_NEWS_AUTH_PASS)){
            //创建app端文章数据
            ResponseResult responseResult = wmNewsAutoScanService.saveAppArticle(wmNews);
            if(responseResult.getCode().equals(200)){
                wmNews.setArticleId((Long) responseResult.getData());
                wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
                updateById(wmNews);
            }
        }

        //4.返回
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
